use alloc::string::String;
use rmpv::Value as RValue;

pub fn from_slice_with_null_to_str(s: &[u8]) -> &str {
    unsafe {
        for i in 0..s.len() {
            if s[i] == 0 {
                return alloc::str::from_utf8_unchecked(&s[..i]);
            }
        }
        alloc::str::from_utf8_unchecked(s)
    }
}

pub fn from_slice_with_null_to_string(s: &[u8]) -> String {
    String::from(from_slice_with_null_to_str(s))
}

pub fn find_rvalue_kv<'a>(root: &'a RValue, key: &'a str) -> Option<&'a RValue> {
    if root.is_map() {
        for (k, v) in root.as_map().unwrap() {
            if k.is_str() && k.as_str().unwrap() == key {
                return Some(v);
            }
        }
    }
    None
}

pub fn copy_slice(src: &[u8], dst: &mut [u8]) {
    let len = if src.len() + 1 > dst.len() {
        dst.len() - 1
    } else {
        src.len()
    };
    unsafe { core::ptr::copy(src.as_ptr(), dst.as_mut_ptr(), len) };
    dst[len] = 0;
}
